<?php
namespace App\Http\Controllers\SysAdmin;

use App\Models\AttendanceSet;
use App\Models\Feedback;
use App\Models\FeedbackDetail;
use App\Models\FeedbackSetDetail;
use App\Models\RewardPunishSetDetail;
use App\Models\RoleUser;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Response;
use Illuminate\Support\Facades\Input;
use App\Models\User;
use App\Models\Achievement;
use App\Models\Company;
use App\Models\RewardPunishSet;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
class FeedbackController extends BaseController
{
    protected $role;


    public function __construct() {
        parent::__construct();
        $this->role = RoleUser::where('user_id',$this->user->id)->where('corpid',$this->corpid)->whereIn('role_id',['9'])->get();
        if(count($this->role) == 0){
            abort(403,'您没有权限访问该页面');
        }
    }
    
    

    //月度意见名称初始化界面
    public function getInit(Request $request)
    {
        $feedback = Feedback::where('corpid',$this->corpid)->get();
        if(count($feedback) >= 5){
            return '月度意见初始化完成后不可修改';
        }
        $view = 'sysadmin.opinion-init';
        return view($view);
    }


    //初始化五项意见反馈
    public function postInitFeedback(Request $request)
    {
        $result = array(
            'status'        => 'success',
            'msg'           => 'ok',
            'data'          => '',
            'redirectUrl'   => ''
        );

        $default = array(
            '很好'=>'5',
            '较好'=>'4',
            '正常'=>'3',
            '较差'=>'2',
            '很差'=>'1',
        );

        $year_param = date('Y');
        if($year_param <= 0){
            $year_param = date('Y');
        }
        $names = $request->input('name');
        $names = json_decode($names);
        if(count($names) < 5){
            $result['status'] = 'fail';
            $result['msg'] = '月度意见反馈项至少为五项';
            return Response::json($result);
        }

        DB::beginTransaction();
        try{
            $exists = Feedback::where('corpid',$this->corpid)->get();
            if(count($exists) >= 5){
                $result['status'] = 'fail';
                $result['msg'] = '系统已存在该企业的月度意见反馈项，不可重复创建';
                return Response::json($result);
            }
            foreach ($names as $k=>$n){
                if(empty($n)){
                    $result['status'] = 'fail';
                    $result['msg'] = '月度意见反馈项名称不能为空';
                    return Response::json($result);
                }
                $n = trim($n);
                $feedback = new Feedback();
                $feedback->corpid = $this->corpid;
                $feedback->name = $n;
                $feedback->year_param = $year_param;
                $feedback->detail = serialize($default);
                $feedback->save();

                foreach ($default as $ky=>$v){
                    $set_detail = new FeedbackSetDetail();
                    $set_detail->set_id = $feedback->id;
                    $set_detail->set_name = $ky;
                    $set_detail->set_value = $v;
                    $set_detail->save();
                }
            }

            $default_jc = array(
                '高级'=>'5',
                '中级'=>'3',
                '低级'=>'1',
            );

            $reward = new RewardPunishSet();
            $reward->kind = 1;
            $reward->year_param = $year_param;
            $reward->corpid = $this->corpid;
            $reward->detail = serialize($default_jc);
            $reward->save();
            foreach ($default_jc as $ky=>$vy){
                $set = new RewardPunishSetDetail();
                $set->set_id = $reward->id;
                $set->set_name = $ky;
                $set->set_value = $vy;
                $set->save();
            }

            $punish = new RewardPunishSet();
            $punish->kind = 2;
            $punish->year_param = $year_param;
            $punish->corpid = $this->corpid;
            $punish->detail = serialize($default_jc);
            $punish->save();
            foreach ($default_jc as $ky=>$vy){
                $set = new RewardPunishSetDetail();
                $set->set_id = $punish->id;
                $set->set_name = $ky;
                $set->set_value = $vy;
                $set->save();
            }

            //检查是否年份一致，防止跨年
            $att_set = AttendanceSet::where('year_param',$year_param)->where('corpid',$this->corpid)->first();
            if(empty($att_set)){
                $att_set = AttendanceSet::where('corpid',$this->corpid)->orderBy('year_param','desc')->first();
                $att_set->year_param = $year_param;
                $att_set->save();
            }


            $company = Company::where('id',$this->corpid)->first();
            $company->init_index = 2;
            $company->from_year = $year_param;
            $company->to_year = $year_param;
            $company->years_array = implode(',',[$year_param]);
            $company->save();

        }catch (\PDOException $e) {
            DB::rollback();
            Log::info($e->getMessage());
            $result['msg'] = '提交失败,数据有误';
            return Response::json($result);
        }
        DB::commit();
        $result['msg'] = '月度意见反馈项保存成功!';
        return Response::json($result);
    }


    //展示意见项等级及分值
    public function getFeedback(Request $request)
    {
        $feedid = $request->input('feedid',0);
        if($feedid < 0){
            return '该项id参数有误';
        }

        $year_param = $request->input('year', 0);
        $company = Company::where('id',$this->corpid)->first();
        if(!is_positive_int($year_param)){
            $year_param = getCurrentYear();
        }
        if(!in_array($year_param,explode(',',$company->years_array))){
            $year_param = $company->from_year;
        }

        $years = explode(',',$company->years_array);
        rsort($years);
        $now = date('Y') + 10;
        $yearlist = array();
        foreach($years as $y){
            $yearlist[] = array(
                'id'=>$y,
                'value'=>$y.'年',
            );
        }
        $yearlist = json_encode($yearlist);

        if($feedid == 0){
            $detail = Feedback::where('year_param',$year_param)->where('corpid',$this->corpid)->first();
        }else{
            $detail = Feedback::find($feedid);
        }
        if(empty($detail)){
            return '该意见项不存在';
        }
        if($detail->corpid != $this->corpid){
            return '您没有权限查看该意见项';
        }
        $names = Feedback::where('year_param',$year_param)->where('corpid',$this->corpid)->select('id','name')->get();
        foreach ($names as $n){
            $name[] = array(
                'title'=>$n->name,
                'value'=>$n->id,
            );
        }
        $name = json_encode($name);
        $view = 'sysadmin.opinion-set';
        return view($view)
            ->with('year_param', $year_param)
            ->with('yearlist', $yearlist)
            ->with('names',$name)
            ->with('feedback',$detail);
    }


    //修改意见项等级及分值
    public function postModifyFeedback(Request $request)
    {
        $result = array(
            'status'        => 'success',
            'msg'           => 'ok',
            'data'          => '',
            'redirectUrl'   => ''
        );
        $feedid = $request->input('feedid',0);
        if($feedid <= 0){
            $result['status'] = 'fail';
            $result['msg'] = '意见项id参数有误';
            return Response::json($result);
        }
        $year_param = $request->input('year', 0);
        $company = Company::where('id',$this->corpid)->first();
        if(!is_positive_int($year_param)){
            $year_param = getCurrentYear();
        }
        if(!in_array($year_param,explode(',',$company->years_array))){
            $year_param = $company->from_year;
        }
        $detail = Feedback::where('year_param',$year_param)->find($feedid);
        if(empty($detail)){
            $result['status'] = 'fail';
            $result['msg'] = '该意见项不存在';
            return Response::json($result);
        }
        if($detail->corpid != $this->corpid){
            $result['status'] = 'fail';
            $result['msg'] = '您没有权限查看该意见项';
            return Response::json($result);
        }

        $feed_name = $request->input('feed_name','');
        $feed_score = $request->input('feed_score','');
        if(empty($feed_name) || empty($feed_score)){
            $result['status'] = 'fail';
            $result['msg'] = '等级名称或分值参数错误';
        }
        $feed_name = json_decode($feed_name);
        $feed_score = json_decode($feed_score);
        $feed_array = array();
        foreach ($feed_name as $k=>$v){
            if(empty($v) || !isset($feed_score[$k])){
                $result['status'] = 'fail';
                $result['msg'] = '等级名称或分值不能为空';
                return Response::json($result);
            }
            $feed_array[trim($v)] = intval(trim($feed_score[$k]));
        }
        $detail->detail = serialize($feed_array);
        $detail->save();
        
        $result['msg'] = '修改保存成功';
        return Response::json($result);
    }



    //修改名称
    public function postModifyFeedbackName(Request $request)
    {
        $result = array(
            'status'        => 'success',
            'msg'           => 'ok',
            'data'          => '',
            'redirectUrl'   => ''
        );
        $feedid = $request->input('feedid',0);
        if(!is_positive_int($feedid)){
            $result['status'] = 'fail';
            $result['msg'] = '意见项id参数有误';
            return Response::json($result);
        }
        $detail = Feedback::find($feedid);
        if(empty($detail)){
            $result['status'] = 'fail';
            $result['msg'] = '该意见项不存在';
            return Response::json($result);
        }
        if($detail->corpid != $this->corpid){
            $result['status'] = 'fail';
            $result['msg'] = '您没有权限查看该意见项';
            return Response::json($result);
        }

        $feed_name = $request->input('name','');

        if(empty($feed_name)){
            $result['status'] = 'fail';
            $result['msg'] = '名称错误';
        }

        $detail->name = $feed_name;
        $detail->save();

        $result['msg'] = '修改成功';
        return Response::json($result);
    }


   
}


